package com.qiaofang.applet.service.member.service.impl;

import com.qiaofang.applet.common.base.MongoBaseService;
import com.qiaofang.applet.common.client.weixin.WxService;
import com.qiaofang.applet.common.client.weixin.model.WxAuthResponse;
import com.qiaofang.applet.common.client.weixin.model.WxDecryptPhone;
import com.qiaofang.applet.common.client.weixin.model.WxProperties;
import com.qiaofang.applet.common.constant.CommonConstant;
import com.qiaofang.applet.common.context.QfContextHolder;
import com.qiaofang.applet.common.dto.SmsDto;
import com.qiaofang.applet.common.exception.BusinessException;
import com.qiaofang.applet.common.util.*;
import com.qiaofang.applet.service.member.config.AppletLoginProperties;
import com.qiaofang.applet.service.member.config.LoginCodeEnum;
import com.qiaofang.applet.service.member.domain.Employee;
import com.qiaofang.applet.service.member.domain.Member;
import com.qiaofang.applet.service.member.domain.WxFollowUsers;
import com.qiaofang.applet.service.member.repository.MemberRepository;
import com.qiaofang.applet.service.member.repository.WxFollowUsersRepository;
import com.qiaofang.applet.service.member.service.DepartmentService;
import com.qiaofang.applet.service.member.service.EmployeeService;
import com.qiaofang.applet.service.member.service.MemberService;
import com.qiaofang.applet.service.member.service.dto.*;
import com.qiaofang.applet.service.member.service.mapstruct.MemberMapper;
import com.qiaofang.applet.service.other.domain.Corporation;
import com.qiaofang.applet.service.other.domain.SmsPlatformConfig;
import com.qiaofang.applet.service.other.repository.CorporationRepository;
import com.qiaofang.applet.service.other.service.CityCompanyService;
import com.qiaofang.applet.service.other.service.YxImUserService;
import com.wf.captcha.base.Captcha;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.repository.support.PageableExecutionUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * @author daiyuxiang
 */
@Slf4j
@Service
public class MemberServiceImpl extends MongoBaseService<Member, String> implements MemberService {

    @Autowired
    private RedisUtil redisUtil;

    @Autowired
    private SmsUtil smsUtil;

    private final MemberRepository repository;

    @Autowired
    private CorporationRepository corporationRepository;

    @Autowired
    private CityCompanyService cityCompanyService;

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private MemberMapper memberMapper;

    @Autowired
    private EmployeeService employeeService;

    @Autowired
    private AppletLoginProperties loginProperties;

    @Autowired
    private WxService wxService;

    @Autowired
    private DepartmentService departmentService;

    @Autowired
    private YxImUserService yxImUserService;

    @Autowired
    private WxFollowUsersRepository wxFollowUsersRepository;

    @Autowired
    public MemberServiceImpl(MemberRepository repository) {
        super(repository);
        this.repository = repository;
    }


    @Override
    public Page<MemberDto> findByParams(MemberQueryDto requestDto, Pageable pageable) {
        Query query = createFindQuery(requestDto);

        long count = mongoTemplate.count(query, Member.class);
        List<Member> list = new ArrayList<>();
        if (count > 0) {
            list = mongoTemplate.find(query.with(pageable), Member.class);
        }
        return PageableExecutionUtils.getPage(memberMapper.toDto(list), pageable, () -> count);
    }

    @Override
    public Map<String, Member> getMemberMap(Set<String> memberIds) {
        Query query = new Query().addCriteria(Criteria.where("id").in(memberIds));
        List<Member> list = mongoTemplate.find(query, Member.class);
        Map<String, Member> map = list.stream().collect(Collectors.toMap(Member::getId, Function.identity()));
        return map;
    }


    private Query createFindQuery(MemberQueryDto queryDto) {
        Query query = new Query();
        query.addCriteria(Criteria.where("corporationCode").is(queryDto.getCorporationCode()));
        if (StringUtils.isNotEmpty(queryDto.getMemberCityName())) {
            query.addCriteria(Criteria.where("memberCityName").regex(".*?" + queryDto.getMemberCityName() + ".*"));
        }
        if (queryDto.getRegisterBeginDate() != null && queryDto.getRegisterEndDate() != null) {
            query.addCriteria(Criteria.where("registerTime").gte(queryDto.getRegisterBeginDate()).lt(queryDto.getRegisterEndDate()));
        }
        if (queryDto.getLastLoginBeginDate() != null && queryDto.getLastLoginEndDate() != null) {
            query.addCriteria(Criteria.where("lastLoginTime").gte(queryDto.getLastLoginBeginDate()).lt(queryDto.getLastLoginEndDate()));
        }
        return query;
    }

    @Override
    public String getMemberPhone(String memberId) {
        String memberPhoneKey = RedisKeyUtil.getMemberPhoneKey(memberId);
        Object obj = redisUtil.get(memberPhoneKey);
        if (obj != null) {
            return (String) obj;
        }
        Optional<Member> optional = repository.findById(memberId);
        if (optional.isPresent()) {
            redisUtil.set(memberPhoneKey, optional.get().getMobilePhone());
            return optional.get().getMobilePhone();
        }
        return "";
    }


    @Override
    public boolean sendCaptcha(SendCaptchaDto sendCaptchaDto) {
        String mobilePhone = sendCaptchaDto.getMobilePhone();
        Integer source = sendCaptchaDto.getSource();
        if (!RegexUtils.checkMobile(mobilePhone)) {
            throw new BusinessException("手机号码非法");
        }
        if (source == 2) {
            //校验图片验证码
            String picCaptchaUuid = sendCaptchaDto.getPicCaptchaUuid();
            String picCaptchaValue = sendCaptchaDto.getPicCaptchaValue();
            if (StringUtils.isEmpty(picCaptchaUuid) || StringUtils.isEmpty(picCaptchaValue)) {
                throw new BusinessException("图片验证码参数为空");
            }
            Object obj = redisUtil.get(RedisKeyUtil.getPicCaptchaKey(picCaptchaUuid));
            if (obj == null) {
                throw new BusinessException("图片验证码已失效");
            }
            if (!picCaptchaValue.equals(obj)) {
                throw new BusinessException("图片验证码答案错误");
            }
            redisUtil.del(RedisKeyUtil.getPicCaptchaKey(picCaptchaUuid));
        }
        SmsDto smsDto = getSmsDto();
        String captcha = CaptchaUtil.generateCaptcha(6);
        String[] mobiles = {mobilePhone};
        smsDto.setMobiles(Arrays.asList(mobiles));
        Map<String, Object> templateParam = new HashMap<>();
        templateParam.put("key1", captcha);
        smsDto.setTemplateParam(templateParam);
        if (smsUtil.sendSms(smsDto)) {
            // 验证码有效期5分钟
            redisUtil.set(RedisKeyUtil.getCaptchaKey(mobilePhone), captcha, 5, TimeUnit.MINUTES);
            log.info("发送验证码成功，mobilePhone:{},captcha:{}", mobilePhone, captcha);
            return true;
        }
        log.error("发送验证码失败，发送参数:{}", smsDto.toString());
        return false;
    }

    @Override
    public Map<String, Object> getPicCaptcha() {
        // 获取运算的结果
        Captcha captcha = loginProperties.getCaptcha();
        String uuid = UuidUtil.geneUuidString();
        //当验证码类型为 arithmetic时且长度 >= 2 时，captcha.text()的结果有几率为浮点型
        String captchaValue = captcha.text();
        if (captcha.getCharType() - 1 == LoginCodeEnum.arithmetic.ordinal() && captchaValue.contains(".")) {
            captchaValue = captchaValue.split("\\.")[0];
        }
        // 保存
        redisUtil.set(RedisKeyUtil.getPicCaptchaKey(uuid), captchaValue, loginProperties.getLoginCode().getExpiration(), TimeUnit.MINUTES);
        // 验证码信息
        Map<String, Object> imgResult = new HashMap<String, Object>(2) {{
            put("img", captcha.toBase64());
            put("uuid", uuid);
        }};

        return imgResult;
    }

    @Override
    public MemberLoginDto login(LoginDto loginDto) {
        String corporationCode = QfContextHolder.getContext().getCorporationCode();
        String lat = loginDto.getLat();
        String lng = loginDto.getLng();
        Integer source = loginDto.getSource();
        String phone = loginDto.getMobilePhone();
        String openId = loginDto.getOpenId();
        if (!RegexUtils.checkMobile(phone)) {
            throw new BusinessException("手机号码非法");
        }
        // 1、验证验证码
        String captcha = null;
        try {
            captcha = (String) redisUtil.get(RedisKeyUtil.getCaptchaKey(loginDto.getMobilePhone()));
        } catch (Exception e) {
            log.error("获取redis缓存验证码失败:{}", e);
            throw new BusinessException("验证码无效");
        }
        if (!loginDto.getCaptcha().equals(captcha)) {
            throw new BusinessException("验证码错误");
        }
        //登录成功，清除缓存
        redisUtil.del(RedisKeyUtil.getCaptchaKey(phone));

        //Member member = findByMobilePhoneAndCorporationCode(phone, corporationCode);
        Member member = null;
        //兼容恒信APP端
        if (StringUtils.isNotBlank(openId)) {
            Member openidMember = repository.findFirstByCorporationCodeAndOpenid(corporationCode, openId);
            if (openidMember != null) {
                if (StringUtils.equals(phone, openidMember.getMobilePhone())) {
                    BeanUtils.copyProperties(openidMember,  member = new Member());
                } else {
                    //这里插入新的手机号，即当前微信用户通过别的手机号登录的
                    openidMember.setMobilePhone(phone);
                    BeanUtils.copyProperties(openidMember,  member = new Member());
                }
            } else {
                //根据openid没有信息，说明之前没有登录过或者是之前一直用的是手机号登录
                Member phoneMember = findByMobilePhoneAndCorporationCode(phone, corporationCode);
                if (phoneMember != null) {
                    if (StringUtils.equals(phoneMember.getOpenid(), openId)) {
                        BeanUtils.copyProperties(phoneMember, member = new Member());
                    } else {
                        phoneMember.setOpenid(openId);
                        BeanUtils.copyProperties(phoneMember, member = new Member());
                    }
                }
            }
        } else {
             member = findByMobilePhoneAndCorporationCode(phone, corporationCode);
        }

        String memberCityName = "";
        if (StringUtils.isNotEmpty(lat) && StringUtils.isNotEmpty(lng)) {
            memberCityName = BaiduMapUtil.getCityByLocation(lat, lng);
        }
        Date date = new Date();

        //因可能出现在经纪人数据未同步至小程序，但此登录手机号已经注册过了，经纪人不展示了
        List<Employee> list = employeeService.findByCorporationCodeAndMobilePhone(corporationCode, phone);
        String employeeName = "";
        String deptName = "";
        if (member == null) {
            //注册，校验是否为经纪人，保存数据
            member = new Member();
            member.setMobilePhone(phone);
            member.setName(phone);
            member.setRegisterTime(date);
            member.setLastLoginTime(date);
            member.setSource(source);
            member.setSourceName(source == 1 ? "移动端" : "WEB端");
            member.setMemberType(1);
            member.setMemberTypeName("普通用户");
            member.setMemberCityName(memberCityName);
            member.setCorporationCode(corporationCode);
            member.setOpenid(openId);
            if (!CollectionUtils.isEmpty(list)) {
                Employee employee = list.get(0);
                member.setMemberType(2);
                member.setMemberTypeName("经纪人");
                member.setEmployeeUniqueUuid(employee.getEmployeeUniqueUuid());
                member.setCompanyUuid(employee.getCompanyUuid());
                employeeName = employee.getEmployeeName();
                deptName = employee.getDeptName();
                if (StringUtils.isEmpty(deptName)) {
                    deptName = departmentService.getDeptName(employee.getCorporationCode(), employee.getCompanyUuid(), employee.getDeptUuid());
                }
            }
            member = repository.insert(member);
        } else {
            //如果此时是普通会员的身份，且经纪人表中有数据，则修改身份成经纪人
            if (member.getMemberType() == 1 && !CollectionUtils.isEmpty(list)){
                Employee employee = list.get(0);
                member.setMemberType(2);
                member.setMemberTypeName("经纪人");
                yxImUserService.memberToEmp(member.getId(), employee.getEmployeeUniqueUuid());
            }
            //如果此时是经纪人的身份，且经纪人表中无数据，则修改身份成普通用户
            if (member.getMemberType() == 2 && CollectionUtils.isEmpty(list)){
                String employeeUniqueUuid = member.getEmployeeUniqueUuid();
                member.setMemberType(1);
                member.setMemberTypeName("普通用户");
                member.setEmployeeUniqueUuid(null);
                member.setCompanyUuid(null);
                yxImUserService.empToMember(member.getId(), employeeUniqueUuid);
            }

            member.setMemberCityName(memberCityName);
            member.setLastLoginTime(date);
            //返回经纪人姓名 部门名称
            if (member.getMemberType() == 2){
                Employee employee = list.get(0);
                member.setEmployeeUniqueUuid(employee.getEmployeeUniqueUuid());
                member.setCompanyUuid(employee.getCompanyUuid());
                employeeName = employee.getEmployeeName();
                deptName = employee.getDeptName();
                if (StringUtils.isEmpty(deptName)) {
                    deptName = departmentService.getDeptName(employee.getCorporationCode(), employee.getCompanyUuid(), employee.getDeptUuid());
                }
            }

            repository.save(member);
        }
        // 3、生成token，并将用户信息缓存在redis中
        String token = UuidUtil.geneUuidString();
        if (source == 2) {
            redisUtil.set(RedisKeyUtil.getPcWebTokenKey(token), "1", CommonConstant.TOKEN_TIMEOUT, TimeUnit.MILLISECONDS);
        } else {
            redisUtil.set(RedisKeyUtil.getWebTokenKey(token), "1", CommonConstant.TOKEN_TIMEOUT, TimeUnit.MILLISECONDS);
        }
        return MemberLoginDto.builder()
                .id(member.getId())
                .name(member.getName())
                .mobilePhone(member.getMobilePhone())
                .registerTime(member.getRegisterTime())
                .lastLoginTime(member.getLastLoginTime())
                .cityName(memberCityName)
                .memberType(member.getMemberType())
                .memberTypeName(member.getMemberTypeName())
                .employeeUniqueUuid(member.getEmployeeUniqueUuid())
                .companyUuid(member.getCompanyUuid())
                .token(token)
                .employeeName(employeeName)
                .deptName(deptName)
                .headPortrait(member.getHeadPortrait())
                .openid(member.getOpenid())
                .build();
    }

    /**
     * @return
     */
    private SmsDto getSmsDto() {
        Corporation corporation = corporationRepository.findOneByCorporationCode(QfContextHolder.getContext().getCorporationCode());
        List<SmsPlatformConfig> list = corporation.getSmsPlatformConfig();
        if (CollectionUtils.isEmpty(list)) {
            throw new BusinessException("集团未配置短信模版信息");
        }
        SmsPlatformConfig smsConfig = list.get(0);
        return SmsDto.builder()
                .url(smsConfig.getUrl())
                .token(smsConfig.getToken())
                .secret(smsConfig.getSecret())
                .mainAccountCode(smsConfig.getMainAccountCode())
                .subAccountCode(smsConfig.getSubAccountCode())
                .templateId(smsConfig.getTemplateId())
                .build();
    }

    @Override
    public MemberLoginDto memberSession(String code) {
        MemberLoginDto resDto = new MemberLoginDto();
        String corporationCode = QfContextHolder.getContext().getCorporationCode();
        if (StringUtils.isBlank(corporationCode)) {
            log.error("微信登录失败，未获取到集团code");
            throw new BusinessException("微信登录失败，未获取到集团code");
        }
        //1、获取小程序appid
        Corporation corporation = corporationRepository.findOneByCorporationCode(corporationCode);
        WxProperties config = new WxProperties();
        config.setAppId(corporation.getAuthAppId());
        config.setAppSecret(corporation.getAuthAppSecret());
        WxAuthResponse wxAuth = wxService.getWxAuth(code, config);

        //是否关注公众号
        if (StringUtils.isNotBlank(corporation.getOaAppId()) && StringUtils.isNotBlank(corporation.getOaAppSecret())) {
            if (StringUtils.isBlank(corporation.getOfficialAccountUrl())){
                log.info("公众号引导关注文章url未配置");
            } else {
                resDto.setIsFollow(isFollowWxOA(wxAuth, corporationCode));
                resDto.setOfficialAccountUrl(corporation.getOfficialAccountUrl());
            }
        }

        //2、根据openid获取用户信息
        Query query = new Query();
        Criteria criteria = Criteria.where("corporationCode").is(QfContextHolder.getContext().getCorporationCode());
        criteria.and("openid").is(wxAuth.getOpenid());
        query.addCriteria(criteria);
        Member member = mongoTemplate.findOne(query, Member.class);
        //3、生成移动端token，并将用户信息缓存在redis中
        String token = UuidUtil.geneUuidString();
        redisUtil.set(RedisKeyUtil.getWebTokenKey(token), "1", CommonConstant.TOKEN_TIMEOUT, TimeUnit.MILLISECONDS);
        //4、未查到用户信息时，返回openid和token
        if (member == null) {
            resDto.setOpenid(wxAuth.getOpenid());
            resDto.setToken(token);
            return resDto;
        }
        List<Employee> list = employeeService.findByCorporationCodeAndMobilePhone(corporationCode, member.getMobilePhone());
        //如果此时是普通会员的身份，且经纪人表中有数据，则修改身份成经纪人
        if (member.getMemberType() == 1 && !CollectionUtils.isEmpty(list)) {
            Employee employee = list.get(0);
            member.setMemberType(2);
            member.setMemberTypeName("经纪人");
            yxImUserService.memberToEmp(member.getId(), employee.getEmployeeUniqueUuid());
        }
        //如果此时是经纪人的身份，且经纪人表中无数据，则修改身份成普通用户
        if (member.getMemberType() == 2 && CollectionUtils.isEmpty(list)){
            String employeeUniqueUuid = member.getEmployeeUniqueUuid();
            member.setMemberType(1);
            member.setMemberTypeName("普通用户");
            member.setEmployeeUniqueUuid(null);
            member.setCompanyUuid(null);
            yxImUserService.empToMember(member.getId(), employeeUniqueUuid);
        }
        member.setLastLoginTime(new Date());
        repository.save(member);
        //6、查到用户信息时，返回用户信息
        BeanUtils.copyProperties(member, resDto);
        resDto.setMemberId(member.getId());
        resDto.setOpenid(wxAuth.getOpenid());
        resDto.setToken(token);
        //部门，用于我的页面展示
        if (member.getMemberType() == 2) {
            Employee employee = list.get(0);
            member.setEmployeeUniqueUuid(employee.getEmployeeUniqueUuid());
            member.setCompanyUuid(employee.getCompanyUuid());
            String deptName = employee.getDeptName();
            if (StringUtils.isEmpty(deptName)) {
                deptName = departmentService.getDeptName(employee.getCorporationCode(), employee.getCompanyUuid(), employee.getDeptUuid());
            }
            resDto.setDeptName(deptName);
            resDto.setEmployeeName(employee.getEmployeeName());
        }
        return resDto;
    }

    /**
     * 是否关注公众号
     * @param wxAuth
     * @param corporationCode
     * @return
     */
    private Integer isFollowWxOA(WxAuthResponse wxAuth, String corporationCode) {
        WxFollowUsers wxFollowUsers = wxFollowUsersRepository.findFirstByCorporationCodeAndUnionid(corporationCode, wxAuth.getUnionid());
        return wxFollowUsers == null ? 2 : 1;
    }

    @Override
    public String decryptPhone(DecryptPhoneReqDto reqDto) {
        WxDecryptPhone wxDp = new WxDecryptPhone();
        BeanUtils.copyProperties(reqDto, wxDp);
        String phone = wxService.decryptPhone(wxDp);
        if (StringUtils.isBlank(phone)) {
            throw new BusinessException("获取微信手机号失败");
        }
        return phone;
    }

    @Override
    public MemberLoginDto wxRegist(MemberRegisterReqDto reqDto) {
        String mobilePhone = reqDto.getMobilePhone();
        String openId = reqDto.getOpenId();
        String lat = reqDto.getLat();
        String lng = reqDto.getLng();
        String corporationCode = QfContextHolder.getContext().getCorporationCode();
        String memberCityName = "";
        String employeeName = "";
        String deptName = "";
        if (StringUtils.isNotEmpty(lat) && StringUtils.isNotEmpty(lng)) {
            memberCityName = BaiduMapUtil.getCityByLocation(lat, lng);
        }
        //1、根据手机号或openid查询member
        Query query = new Query();
        Criteria criteria = new Criteria();
        //criteria.orOperator(Criteria.where("mobilePhone").is(mobilePhone), Criteria.where("openId").is(openId));
        //微信登录后续都根据openId去查询，反正后续会判断当前登录的状态
        criteria.and("openid").is(openId);
        Member member = mongoTemplate.findOne(query.addCriteria(criteria).addCriteria(Criteria.where("corporationCode").is(corporationCode)), Member.class);
        Date date = new Date();

        List<Employee> list = employeeService.findByCorporationCodeAndMobilePhone(corporationCode, mobilePhone);

        if (member != null) {
            //2、查询到，判断是否缺少手机号或openid，做一次更新
            member.setMobilePhone(mobilePhone);
            member.setOpenid(openId);
            member.setMemberCityName(memberCityName);
            member.setLastLoginTime(date);

            //如果此时是普通会员的身份，且经纪人表中有数据，则修改身份成经纪人
            if (member.getMemberType() == 1 && !CollectionUtils.isEmpty(list)){
                Employee employee = list.get(0);
                member.setMemberType(2);
                member.setMemberTypeName("经纪人");
                yxImUserService.memberToEmp(member.getId(), employee.getEmployeeUniqueUuid());
            }

            //如果此时是经纪人的身份，且经纪人表中无数据，则修改身份成普通用户
            if (member.getMemberType() == 2 && CollectionUtils.isEmpty(list)){
                String employeeUniqueUuid = member.getEmployeeUniqueUuid();
                member.setMemberType(1);
                member.setMemberTypeName("普通用户");
                member.setEmployeeUniqueUuid(null);
                member.setCompanyUuid(null);
                yxImUserService.empToMember(member.getId(), employeeUniqueUuid);
            }

            //返回经纪人姓名 部门名称
            if (member.getMemberType() == 2){
                Employee employee = list.get(0);
                member.setEmployeeUniqueUuid(employee.getEmployeeUniqueUuid());
                member.setCompanyUuid(employee.getCompanyUuid());
                deptName = employee.getDeptName();
                if (StringUtils.isEmpty(deptName)) {
                    deptName = departmentService.getDeptName(employee.getCorporationCode(), employee.getCompanyUuid(), employee.getDeptUuid());
                }
                employeeName = employee.getEmployeeName();
            }
            repository.save(member);
        } else {
            //4、未查询到，走注册逻辑
            member = new Member();
            member.setMobilePhone(mobilePhone);
            member.setName(mobilePhone);
            member.setRegisterTime(date);
            member.setLastLoginTime(date);
            member.setSource(1);
            member.setSourceName("移动端");
            member.setMemberType(1);
            member.setMemberTypeName("普通用户");
            member.setMemberCityName(memberCityName);
            member.setCorporationCode(corporationCode);
            member.setOpenid(reqDto.getOpenId());
            if (!CollectionUtils.isEmpty(list)) {
                Employee employee = list.get(0);
                member.setMemberType(2);
                member.setMemberTypeName("经纪人");
                member.setEmployeeUniqueUuid(employee.getEmployeeUniqueUuid());
                member.setCompanyUuid(employee.getCompanyUuid());
                employeeName = employee.getEmployeeName();
                deptName = employee.getDeptName();
                //部门
                if (StringUtils.isEmpty(deptName)) {
                    deptName = departmentService.getDeptName(employee.getCorporationCode(), employee.getCompanyUuid(), employee.getDeptUuid());
                }

            }
            member = repository.insert(member);
        }
        String token = UuidUtil.geneUuidString();
        redisUtil.set(RedisKeyUtil.getWebTokenKey(token), "1", CommonConstant.TOKEN_TIMEOUT, TimeUnit.MILLISECONDS);

        //3、返回用户信息
        return MemberLoginDto.builder()
                .id(member.getId())
                .memberId(member.getId())
                .openid(member.getOpenid())
                .name(member.getName())
                .mobilePhone(member.getMobilePhone())
                .registerTime(member.getRegisterTime())
                .lastLoginTime(member.getLastLoginTime())
                .cityName(memberCityName)
                .memberType(member.getMemberType())
                .memberTypeName(member.getMemberTypeName())
                .employeeUniqueUuid(member.getEmployeeUniqueUuid())
                .companyUuid(member.getCompanyUuid())
                .token(token)
                .deptName(deptName)
                .employeeName(employeeName)
                .build();
    }

    @Override
    public Member findByMobilePhoneAndCorporationCode(String mobilePhone, String corporationCode) {
        return repository.findByMobilePhoneAndCorporationCode(mobilePhone, corporationCode);
    }

    @Override
    public void updateHeadPortraitAndName(HeadPortraitAndNameDto headPortraitAndNameDto) {
        Member member = repository.findFirstByCorporationCodeAndOpenid(QfContextHolder.getContext().getCorporationCode(), headPortraitAndNameDto.getOpenId());
        if (member == null) {
            throw new BusinessException("此用户信息不存在");
        }
        member.setName(headPortraitAndNameDto.getWxName());
        member.setHeadPortrait(headPortraitAndNameDto.getHeadPortrait());
        updateById(member);
    }

    @Override
    public void pcwebLogout(String token) {
        if(StringUtils.isNotEmpty(token)) {
            redisUtil.del(RedisKeyUtil.getPcWebTokenKey(token));
        }
    }
}
